package org.example.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.entity.Employee;
import org.example.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;


@Controller
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;


    @RequestMapping("welcomeView")
    public String welcome() {
        return "welcome";
    }


    @RequestMapping("addEmployeeView")
    public String addEmployeeView() {
        return "addEmployee";
    }


    @RequestMapping("updateEmployeeView")
    public String updateEmployeeView() {
        return "updateEmployee";
    }


    @RequestMapping("ajaxWelcomeView")
    public String ajaxWelcomeView() {
        return "welcome_ajax";
    }


    @RequestMapping("restWelcomeView")
    public String restWelcomeView() {
        return "welcome_rest";
    }


    @GetMapping("employeeListView_rest")
    public String employeeListView() {
        return "employeeList_rest";
    }


    @RequestMapping("employeeList")
    @ResponseBody
    public ModelAndView employeeView(int pageNum, int pageSize, ModelAndView mv) {
        PageHelper.startPage(pageNum, pageSize);
        List<Employee> employees = employeeService.queryAll();
        PageInfo pageInfo = new PageInfo(employees, 10);
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("employeeList");
        return mv;
    }


    @RequestMapping("addEmployee")
    public String addEmployee(Employee employee) {
        Boolean isSuccess = employeeService.addEmployee(employee);
        return getWelcomeView(isSuccess);
    }


    @RequestMapping("updateEmployee")
    public String updateEmployee(Employee employee) {
        Boolean isSuccess = employeeService.updateEmployee(employee);
        return getWelcomeView(isSuccess);
    }


    @RequestMapping("deleteEmployee")
    public String deleteEmployee(int id) {
        Boolean isSuccess = employeeService.deleteEmployee(id);
        return getWelcomeView(isSuccess);
    }


    private String getWelcomeView(Boolean isSuccess) {
        if (isSuccess) {
            return "redirect:welcomeView";
        } else {
            return "失败";
        }
    }

}
